﻿using KAKA.Repository;
using KAKA.Service;
using Morus;
using Morus.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KAKA.Infrastructure
{
    public class SendMail : BaseBackgroundTask
    {
        private SubscriptionToken _registrationToken;
        private SubscriptionToken _emailVerificationToken;

        public SendMail()
            : base(IoC.Resolve<IEventAggregator>())
        {
            EmailSender = IoC.Resolve<IEmailSender>();
            UserRepository = IoC.Resolve<IUserRepository>();
        }

        public IEmailSender EmailSender { get; private set; }
        public IUserRepository UserRepository { get; private set; }

        protected override void OnStart()
        {
            if (!IsRunning)
            {
                _registrationToken = Subscribe<RegistrationEvent, RegistrationEventArgs>(Registration);
                _emailVerificationToken = Subscribe<EmailVerificationEvent, EmailVerificationEventArgs>(EmailVerification);
            }
        }

        private void Registration(RegistrationEventArgs eventArgs)
        {
            EmailSender.SendRegistration(eventArgs.User.Email, eventArgs.User.Member.Nickname, eventArgs.Token.Shrink());
        }

        private void EmailVerification(EmailVerificationEventArgs eventArgs)
        {
            EmailSender.SendEmailVerification(eventArgs.Email, eventArgs.User.Member.Nickname, eventArgs.Token.Shrink());
        }

        protected override void OnStop()
        {
            if (IsRunning)
            {
                Unsubscribe<EmailVerificationEvent>(_registrationToken);
                Unsubscribe<EmailVerificationEvent>(_emailVerificationToken);
            }
        }
    }
}
